package cn.tedu.reflect;

import cn.tedu.scheduled.SpringScheduledTasks;
import org.springframework.scheduling.annotation.Scheduled;

import java.lang.reflect.Method;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
//剖析Spring Task底层执行原理：借助反射技术进行任务调度
public class RelectDemo01 {
    public static void main(String[] args) throws NoSuchMethodException {
        //1.反射的入口
        Class<SpringScheduledTasks> cls
                = SpringScheduledTasks.class;
        //2.获取方法对象
        Method fixedRateTask =
                cls.getDeclaredMethod("fixedRateTask");
        //3.获取方法上的注解对象
        Scheduled annotation =
                fixedRateTask.getAnnotation(Scheduled.class);
        //4.获取注解上的属性值
        long l = annotation.fixedRate();
        //System.out.println(l);
        //5.基于任务调度，执行对象方法
        SpringScheduledTasks tasks=new SpringScheduledTasks();
        Executors.newScheduledThreadPool(1)
                .scheduleAtFixedRate(new Runnable() {
                    @Override
                    public void run() {
                        //反射调用方法来执行
                        try{fixedRateTask.invoke(tasks);}catch (Exception e){}
                    }
                },0,l, TimeUnit.MILLISECONDS);

    }
}
